import axios from 'axios'
import store from '@/store'
import SettingMer from '@/libs/settingMer'
import Cookies from 'js-cookie'
import {
  getToken,
  removeToken
} from '@/utils/auth'

const instance = axios.create({
  baseURL: SettingMer.https,
  timeout: 60000
})

// 请求拦截
instance.interceptors.request.use(config => {

  const hasToken = getToken()
  console.log(hasToken,"77777777777777999")
  // 设置统一的请求头：如何配置访问有token的接口
  if (hasToken) {
      config.headers.Authorization = hasToken
  }

  return config
}, error => {
  return Promise.reject(error)
})

// 响应拦截
instance.interceptors.response.use(response => {
  // console.log(response, "66666666668888")
  return response
}, error => {
  Message.error(error.response.data)

  // 获取错误状态码，token失效
  const {
    status
  } = error.response.status
  if (status == 401) {
    console.log(response, "66666666662222")
    Message.error('token失效，请重新登录')
    // 清除token
    removeToken()

    // 重新跳转到login页面
    router.push('/admin/login')
  }

  return Promise.reject(error)
})



const defaultOpt = {
  login: true
}

function baseRequest(options) {
  const token = store.getters.token
  const headers = options.headers || {}
  if (token) {
    headers['Authorization'] = token
    options.headers = headers
  }
  return new Promise((resolve, reject) => {
    instance(options).then(res => {
      // console.log(res)
      const data = res.data || {}
      // console.log("555")
      if (res.status !== 200) {
        console.log("请求失败")
        return reject({
          message: '请求失败',
          res,
          data
        })
      }
      // ------------------------------------
      if ([410000, 410001, 410002, 40000].indexOf(data.status) !== -1) {
        // console.log("请求")
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      }
      // ------------------------------------
      else if (data.code === 200) {
        // console.log("成功")
        return resolve(data)
      }
      // ------------------------------------
      else {
        // console.log(data.status)
        return reject({
          message: data.message,
          res,
          data
        })
      }
    }).catch(message => reject({
      message
    }));
  })
}
/**
 * http 请求基础类
 * 参考文档 https://www.kancloud.cn/yunye/axios/234845
 *
 */
const request = ['post', 'put', 'patch', 'delete'].reduce((request, method) => {
  /**
   *
   * @param url string 接口地址
   * @param data object get参数
   * @param options object axios 配置项
   * @returns {AxiosPromise}
   */
  // console.log("乱写")
  request[method] = (url, data = {}, options = {}) => {
    return baseRequest(
      Object.assign({
        url,
        data,
        method
      }, defaultOpt, options)
    )
  }
  return request
}, {});

['get', 'head'].forEach(method => {
  /**
   *
   * @param url string 接口地址
   * @param params object get参数
   * @param options object axios 配置项
   * @returns {AxiosPromise}
   */
  request[method] = (url, params = {}, options = {}) => {
    return baseRequest(
      Object.assign({
        url,
        params,
        method
      }, defaultOpt, options)
    )
  }
})





export default request